﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;

namespace CsharpTrainer.Domain.Concurrency.Progress
{
    public class PdfImport : IImport
    {
        public Task ImportFilesAsync(string dataDirectory)
        {
            return ImportFilesAsync(dataDirectory, CancellationToken.None);
        }

        public Task ImportFilesAsync(string dataDirectory, CancellationToken ct)
        {
            return ImportFilesAsync(dataDirectory, ct, new Progress<ImportProgress>());
        }
        
        public Task ImportFilesAsync(string dataDirectory,
            CancellationToken ct, IProgress<ImportProgress> progressObserver)
        {
            return Task.Run(() =>
            {
                FileInfo[] files = new DirectoryInfo(dataDirectory).GetFiles("*.pdf");
                int nFileProcessed = 0;
                foreach (FileInfo file in files)
                {
                    string fileName = string.Empty;
                    nFileProcessed++;

                    Mutex fileMutex = new Mutex(false, file.Name);
                    bool cancelled = (WaitHandle.WaitAny(new WaitHandle[] { fileMutex, ct.WaitHandle }) == 1);

                    try
                    {
                        ct.ThrowIfCancellationRequested();
                        fileName = file.FullName;
                    }
                    finally
                    {
                        fileMutex.ReleaseMutex();
                    }

                    double progress = (double)nFileProcessed / (double)files.Length * 100.0;

                    progressObserver.Report(new ImportProgress((int)progress, file.Name));
                    InternalProcess(fileName);
                    
                }
            }, ct);
        }

        private void InternalProcess(string fileName)
        {
            Thread.Sleep(1000);
        }
    }
}